// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

(function($){
  // Pagination stuff!
  var results = new Object();  // save the ajax results in here
  
  $(function(){
    if($(".pagination").length > 0){
      if(page_size == undefined) throw "Expecting page_size to be defined!";
      if(total == undefined) throw "Expecting total to be defined!";
      if(results_url == undefined) throw "Expecting results_url to be defined!";
      if (window.pag_options == undefined) {
        pag_options = {};
      }
      
      var options;
      $.history.init(function(hash){
        // This gets called on page load and when you click a pagination link
        options = {
          page: parseInt(hash.substring("page".length))
        };
        if(isNaN(options.page)) options.page = 0;
        
        options = $.extend(options, pag_options);
        
        if(results[options.page]){
          $("#results").html(results[options.page]);
        } else {
          $.get(results_url, options, function(data){
            $("#results").html(data);
            results[options.page] = data;
          });
        }
        
        var start = options.page * page_size + 1;
        var end = start + page_size - 1;
        end = end > total ? total : end;
        
        $("#page_start_count").text(start);
        $("#page_end_count").text(end)
      });
      
      $("#pagination_helper").pagination(total, {
        items_per_page: page_size,
        link_to: "#page__id__",
        current_page: options.page,
        callback: function(page_number, container){
          $("#results").text("Loading page " + (page_number+1) + ", please wait...");
        }
      });
    }
    
    // anti-forgery stuff!
    $(document).ajaxSend(function(event, request, settings) {
      if (typeof(AUTH_TOKEN) == "undefined") return;
      // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
      settings.data = settings.data || "";
      settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
    });
  });
})(jQuery);